package com.vincent.kdp.Activity;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;

import com.google.gson.Gson;
import com.vincent.baseapp.util.SPUtil;
import com.vincent.kdp.PostUrl;
import com.vincent.kdp.R;
import com.vincent.kdp.bean.ApiResponse;
import com.vincent.kdp.bean.BusFacility;
import com.vincent.kdp.bean.QueryFacility;
import com.vincent.kdp.ui.other.MainActivity;
import com.vincent.kdp.util.BaseParam;
import com.vincent.kdp.util.Function;
import com.vincent.kdp.util.GsonUtils;
import com.vincent.kdp.util.PollingService;
import com.vincent.kdp.util.PollingUtils;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Timer;

public class WelcomeActivity extends Activity {
    private static int fd = -1;
    private String comStr="/dev/ttyS1";
    private int baudRate = 57600;
    private static byte flagCrc= 0x00;
    Function fun = new Function();
    private static boolean loopFlag=true;
    private static String currentBarCode="";
    static ArrayList<HashMap<String, String>> tagList;
    private static final String SHARE_APP_TAG ="tt" ;

    private Handler mHandler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_welcom);

//        TelephonyManager telephonyManager = (TelephonyManager)getSystemService( Context.TELEPHONY_SERVICE );
        Log.i("code","设备号码："+android.os.Build.SERIAL);
//        Log.i("code","设备号码2："+telephonyManager.getSimSerialNumber());
//        BaseParam.setDeviceId(telephonyManager.getSimSerialNumber());
        BaseParam.setDeviceId(android.os.Build.SERIAL);

//        System.out.println("设备号码----"+telephonyManager.getDeviceId());

        //每次启动清空登录信息
        SPUtil.remove("username");


        //当计时结束,跳转至主界面
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                hasOpenFacility();
            }
        }, 2000);

        PollingUtils.startPollingService(this, 1800, PollingService.class, PollingService.ACTION);
    }


    public boolean isConnect() {
        ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        if ((networkInfo != null) && (networkInfo.isConnected())) {
            return true;
        }

        return false;
    }

    private  void getDifferent(){
        RequestParams params = new RequestParams (PostUrl.GET_DIFFERENT_TITLE);
        params.addBodyParameter("number", BaseParam.getDeviceId());
        x.http().post(params, new Callback.CommonCallback<String>() {
                    @Override
                    public void onSuccess(String result) {
                        Log.i("HttpUtil----",result);
                        //System.out.println("result"+result);
                        Gson gson = GsonUtils.build();
                        ApiResponse apiResponse = gson.fromJson(result, ApiResponse.class);
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        Toast.makeText(WelcomeActivity.this, "网络请求异常", Toast.LENGTH_SHORT);
                        dialog("网络请求异常");
                    }

                    @Override
                    public void onCancelled(CancelledException cex) {

                    }

                    @Override
                    public void onFinished() {

                    }
                }
        );
    }
    private void doFacilityRequest() {
        RequestParams params = new RequestParams (PostUrl.QUERY_FACILITY);
        params.addBodyParameter("number", BaseParam.getDeviceId());

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.i("HttpUtil-----2",result);
                System.out.println("HttpUtil-----2"+result);
                Gson gson = GsonUtils.build();
                ApiResponse apiResponse = gson.fromJson(result, ApiResponse.class);
                if(apiResponse.getMsg().equals("该设备已被禁用")){
                    Toast.makeText(WelcomeActivity.this, "该设备已被禁用,请联系管理员", Toast.LENGTH_SHORT).show();
                    finish();
                    return;
                }
                if (apiResponse.isSuccess()) {
                    QueryFacility queryFacility = gson.fromJson(result, QueryFacility.class);
                    BusFacility facility = queryFacility.getData();
                    if (facility != null) {
                        //判断是否是第一次Status=0，是则获取公司ID跳转部门选择页面。否则直接跳转主页
                        if(facility.getStatus()==1){
                            Intent intent = new Intent(WelcomeActivity.this, MainActivity.class);
                            startActivity(intent);
                            finish();
                        }else {
                            int companyId=facility.getCompanyId();
                            Toast.makeText(WelcomeActivity.this, "该设备未绑定门店，请选择门店", Toast.LENGTH_SHORT);
                            Intent intent=new Intent(WelcomeActivity.this,BumenActivity.class);
                            Bundle bundle=new Bundle();
                            bundle.putString("id", String.valueOf(companyId));
                            intent.putExtras(bundle);
                            startActivity(intent);
                            finish();
                        }
                    } else {
                        Toast.makeText(WelcomeActivity.this, "该设备已绑定,但是存在异常,请联系管理员", Toast.LENGTH_SHORT);
                        dialog("该设备已绑定,但是存在异常,请联系管理员");
                    }
                } else {
                   // Toast.makeText(WelcomeActivity.this, "系统错误", Toast.LENGTH_SHORT).show();
                    //finish();
                    dialog(apiResponse.getMsg());

                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(WelcomeActivity.this, "网络请求异常", Toast.LENGTH_SHORT);
                dialog("网络请求异常");
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
    /**
     * 查询设备激活状态
     */
    private void hasOpenFacility() {
        //to do : will be optimized in future.
        if (isConnect()) {

            System.out.println("1111111");
           doFacilityRequest();
            getDifferent();
        } else {

            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                   doFacilityRequest();
                    getDifferent();
                }
            }, 2000);
        }
    }

    public String getDeviceId(){
        TelephonyManager telephonyManager = (TelephonyManager)getSystemService( Context.TELEPHONY_SERVICE );
        String deviceId =telephonyManager.getDeviceId();

        return deviceId;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //Stop polling service
        System.out.println("Stop polling service...");
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
        PollingUtils.stopPollingService(this, PollingService.class, PollingService.ACTION);
    }


    public void dialog(String msg){
        AlertDialog.Builder builder = new AlertDialog.Builder(WelcomeActivity.this);
        builder.setTitle("提示");
        builder.setMessage(msg);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }



}

